<?php
define("EW_PAGE_ID", "register", TRUE); // Page ID
?>
<?php 
session_start(); // Initialize session data
ob_start(); // Turn on output buffering
?>
<?php include "osj-ewcfg50.php" ?>
<?php include "osj-ewmysql50.php" ?>
<?php include "osj-phpfn50.php" ?>
<?php include "osj-osj2dusersinfo.php" ?>
<?php include "osj-userfn50.php" ?>
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
?>
<?php

// Open connection to the database
$conn = ew_Connect();
?>
<?php
$Security = new cAdvancedSecurity();
?>
<?php

// Common page loading event (in userfn*.php)
Page_Loading();
?>
<?php

// Page load event, used in current page
Page_Load();
?>
<?php
$bUserExists = FALSE;

// Create form object
$objForm = new cFormObj();
if (@$_POST["a_register"] <> "") {

	// Get action
	$osj2Dusers->CurrentAction = $_POST["a_register"];
	LoadFormValues(); // Get form values
} else {
	$osj2Dusers->CurrentAction = "I"; // Display blank record
	LoadDefaultValues(); // Load default values
}

// Handle email activation
if (@$_GET["action"] <> "") {
	$sAction = $_GET["action"];
	$sEmail = $_GET["email"];
	$qs = new cQueryString();
	$sApprovalCode = $qs->getValue("code");
	if ($sEmail == TEAdecrypt($sApprovalCode, EW_RANDOM_KEY)) {
		if (strtolower($sAction) == "confirm") { // Email activation
			if (ActivateEmail($sEmail)) { // activate this email
				$_SESSION[EW_SESSION_MESSAGE] = "Your account is activated"; // Set message acount activated
				Page_Terminate("osj-login.php"); // Go to login page
			}
		}
	}
	if (@$_SESSION[EW_SESSION_MESSAGE] == "") {
		$_SESSION[EW_SESSION_MESSAGE] = "Activation failed"; // Set activate failed message
	}
	Page_Terminate("osj-login.php"); // Go to login page
}
switch ($osj2Dusers->CurrentAction) {
	case "I": // Blank record, no action required
		break;
	case "A": // Add

		// Check for Duplicate User ID
		$sFilter = "(`user_email` = '" . ew_AdjustSql($osj2Dusers->user_email->CurrentValue) . "')";

		// Set up filter (Sql Where Clause) and get Return Sql
		// Sql constructor in osj2Dusers class, osj2Dusersinfo.php

		$osj2Dusers->CurrentFilter = $sFilter;
		$sUserSql = $osj2Dusers->SQL();
		if ($rs = $conn->Execute($sUserSql)) {
			if (!$rs->EOF) {
				$bUserExists = TRUE;
				RestoreFormValues(); // Restore form values
				$_SESSION[EW_SESSION_MESSAGE] = "User Already Exists!"; // Set user exist message
			}
			$rs->Close();
		}
		if (!$bUserExists) {
			$osj2Dusers->SendEmail = TRUE; // Send email on add success
			if (AddRow()) { // Add record

				// Load user email
				$sReceiverEmail = $osj2Dusers->user_email->CurrentValue;
				if ($sReceiverEmail == "") { // Send to recipient directly
					$sReceiverEmail = EW_RECIPIENT_EMAIL;
					$sBccEmail = "";
				} else { // Bcc recipient
					$sBccEmail = EW_RECIPIENT_EMAIL;
				}

				// Set up email content
				if ($sReceiverEmail <> "") {
					$Email = new cEmail;
					$Email->Load("txt/osj-register.txt");
					$Email->ReplaceSender(EW_SENDER_EMAIL); // Replace Sender
					$Email->ReplaceRecipient($sReceiverEmail); // Replace Recipient
					if ($sBccEmail <> "") $Email->AddBcc($sBccEmail); // Add Bcc
					$Email->ReplaceContent('<!--user_email-->', strval($osj2Dusers->user_email->CurrentValue));
					$Email->ReplaceContent('<!--user_password-->', strval($osj2Dusers->user_password->CurrentValue));
					$Email->ReplaceContent('<!--user_level-->', strval($osj2Dusers->user_level->CurrentValue));
					$sActivateLink = ew_FullUrl() . "?action=confirm";
					$sActivateLink .= "&email=" . $osj2Dusers->user_email->CurrentValue;
					$sActivateLink .= "&code=" . TEAencrypt($osj2Dusers->user_email->CurrentValue, EW_RANDOM_KEY);
					$Email->ReplaceContent("<!--ActivateLink-->", $sActivateLink);
					$Email->Send();
				}
				$_SESSION[EW_SESSION_MESSAGE] = "Registration Successful. An email has been sent to your email address, please click the link in the email to activate your account."; // Activate success
				Page_Terminate("osj-login.php"); // Go to login page
			} else {
				RestoreFormValues(); // Restore form values
			}
		}
}

// Render row
$osj2Dusers->RowType = EW_ROWTYPE_ADD; // Render add
RenderRow();
?>
<?php include "osj-header.php" ?>
<script type="text/javascript">
<!--
var EW_PAGE_ID = "register"; // Page id
var EW_SHOW_HIGHLIGHT = "Show highlight"; 
var EW_HIDE_HIGHLIGHT = "Hide highlight";

//-->
</script>
<script type="text/javascript">
<!--

function ew_ValidateForm(fobj) {
	if (fobj.a_confirm && fobj.a_confirm.value == "F")
		return true;
	var i, elm, aelm, infix;
	var rowcnt = (fobj.key_count) ? Number(fobj.key_count.value) : 1;
	for (i=0; i<rowcnt; i++) {
		infix = (fobj.key_count) ? String(i+1) : "";
		elm = fobj.elements["x" + infix + "_user_email"];
		if (elm && !ew_HasValue(elm)) {
			if (!ew_OnError(elm, "Please enter required field - Email"))
				return false;
		}
		elm = fobj.elements["x" + infix + "_user_email"];
		if (elm && !ew_CheckEmail(elm.value)) {
			if (!ew_OnError(elm, "Users  must provide a valid email address."))
				return false; 
		}
		elm = fobj.elements["x" + infix + "_user_password"];
		if (elm && !ew_HasValue(elm)) {
			if (!ew_OnError(elm, "Please enter required field - Password"))
				return false;
		}
		if (fobj.x_user_password && !ew_HasValue(fobj.x_user_password)) {
			if (!ew_OnError(fobj.x_user_password, "Please enter password"))
				return false; 
		}
		if (fobj.c_user_password.value != fobj.x_user_password.value) {
			if (!ew_OnError(fobj.c_user_password, "Mismatch Password"))
				return false; 
		}
		elm = fobj.elements["x" + infix + "_user_level"];
		if (elm && !ew_HasValue(elm)) {
			if (!ew_OnError(elm, "Please enter required field - User Level"))
				return false;
		}
	}
	return true;
}

//-->
</script>
<script type="text/javascript">
<!--
var ew_DHTMLEditors = [];

//-->
</script>
<script type="text/javascript">
<!--

// js for Popup Calendar
//-->

</script>
<script type="text/javascript">
<!--
var ew_MultiPagePage = "Page"; // multi-page Page Text
var ew_MultiPageOf = "of"; // multi-page Of Text
var ew_MultiPagePrev = "Prev"; // multi-page Prev Text
var ew_MultiPageNext = "Next"; // multi-page Next Text

//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--

// Write your client script here, no need to add script tags.
// To include another .js script, use:
// ew_ClientScriptInclude("my_javascript.js"); 
//-->

</script>
<p><span class="phpmaker">
Registration Page<br><br>
<a href="osj-login.php">Back to Login Page</a>
</span></p>
<?php 
if (@$_SESSION[EW_SESSION_MESSAGE] <> "") {
?>
<p><span class="ewmsg"><?php echo $_SESSION[EW_SESSION_MESSAGE] ?></span></p>
<?php
	$_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message
}
?>
<form name="fosj2Dusersregister" id="fosj2Dusersregister" action="osj-register.php" method="post" onSubmit="return ew_ValidateForm(this);">
<p>
<input type="hidden" name="a_register" id="a_register" value="A">
<table class="ewTable">
	<tr class="ewTableRow">
		<td class="ewTableHeader">Email<span class='ewmsg'>&nbsp;*</span></td>
		<td<?php echo $osj2Dusers->user_email->CellAttributes() ?>><span id="cb_x_user_email">
<input type="text" name="x_user_email" id="x_user_email" title="Email"  size="30" maxlength="255" value="<?php echo $osj2Dusers->user_email->EditValue ?>"<?php echo $osj2Dusers->user_email->EditAttributes() ?>>
</span></td>
	</tr>
	<tr class="ewTableAltRow">
		<td class="ewTableHeader">Password<span class='ewmsg'>&nbsp;*</span></td>
		<td<?php echo $osj2Dusers->user_password->CellAttributes() ?>><span id="cb_x_user_password">
<input type="password" name="x_user_password" id="x_user_password" title="Password" value="<?php echo $osj2Dusers->user_password->EditValue ?>" size="30" maxlength="255"<?php echo $osj2Dusers->user_password->EditAttributes() ?>>
</span></td>
	</tr>
	<!--tr id=""-->
	<tr class="ewTableRow">
		<td class="ewTableHeader">Confirm Password</td>
		<td<?php echo $osj2Dusers->user_password->CellAttributes() ?>>
<input type="password" name="c_user_password" id="c_user_password" title="Password" value="<?php echo $osj2Dusers->user_password->EditValue ?>" size="30" maxlength="255"<?php echo $osj2Dusers->user_password->EditAttributes() ?>>
</td>
	</tr>
<?php if (!$Security->IsAdmin() && $Security->IsLoggedIn()) { // Non system admin ?>
<div<?php echo $osj2Dusers->user_level->ViewAttributes() ?>><?php echo $osj2Dusers->user_level->EditValue ?></div>
<?php } else { ?>
<select id="x_user_level" name="x_user_level"<?php echo $osj2Dusers->user_level->EditAttributes() ?>>
<!--option value="">Please Select</option-->
<?php
if (is_array($osj2Dusers->user_level->EditValue)) {
	$arwrk = $osj2Dusers->user_level->EditValue;
	$rowswrk = count($arwrk);
	for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) {
		$selwrk = (strval($osj2Dusers->user_level->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected" : "";	
?>
<option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>>
<?php echo $arwrk[$rowcntwrk][1] ?>
</option>
<?php
			}
}
?>
</select>
<?php
$sSqlWrk = "SELECT `user_level_id`, `user_level_name` FROM `osj-user_level`";
$sSqlWrk .= " WHERE (" . "`user_level_name` != 'Default' AND `user_level_name`!= 'Administrator'" . ")";
$sSqlWrk = TEAencrypt($sSqlWrk, EW_RANDOM_KEY);
?>
<input type="hidden" name="s_x_user_level" id="s_x_user_level" value="<?php echo $sSqlWrk ?>"><input type="hidden" name="lc_x_user_level" id="lc_x_user_level" value="2"><input type="hidden" name="ld1_x_user_level" id="ld1_x_user_level" value="1"><input type="hidden" name="ld2_x_user_level" id="ld2_x_user_level" value="-1"><input type="hidden" name="lft_x_user_level" id="lft_x_user_level" value="1">
<?php } ?>
</table>
<p>
<input type="submit" name="btnAction" id="btnAction" value=" Register ">
</form>
<script language="JavaScript">
<!--
var f = document.fosj2Dusersregister;
ew_AjaxUpdateOpt(f.x_user_level, f.x_user_level, false);

//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--

// Write your startup script here
// document.write("page loaded");
//-->

</script>
<?php include "osj-footer.php" ?>
<?php

// If control is passed here, simply terminate the page without redirect
Page_Terminate();

// -----------------------------------------------------------------
//  Subroutine Page_Terminate
//  - called when exit page
//  - clean up connection and objects
//  - if url specified, redirect to url, otherwise end response
function Page_Terminate($url = "") {
	global $conn;

	// Page unload event, used in current page
	Page_Unload();

	// Global page unloaded event (in userfn*.php)
	Page_Unloaded();

	 // Close Connection
	$conn->Close();

	// Go to url if specified
	if ($url <> "") {
		ob_end_clean();
		header("Location: $url");
	}
	exit();
}
?>
<?php

// Activate account based on email
function ActivateEmail($email) {
	global $conn, $osj2Dusers;
	$sFilter = "(`user_email` = '" . ew_AdjustSql($email) . "')";
	$osj2Dusers->CurrentFilter = $sFilter;
	$sSql = $osj2Dusers->SQL();
	$conn->raiseErrorFn = 'ew_ErrorFn';
	$rs = $conn->Execute($sSql);
	$conn->raiseErrorFn = '';
	if ($rs === FALSE)
		return FALSE;
	if (!$rs->EOF) {
		$rs->Close();
		$rsnew = array('user_status' => 1); // Auto register
	 	return $conn->Execute($osj2Dusers->UpdateSQL($rsnew));
	} else {
		$_SESSION[EW_SESSION_MESSAGE] = "No records found";
		$rs->Close();
		return FALSE;
	}
}
?>
<?php

// Load default values
function LoadDefaultValues() {
	global $osj2Dusers;
	$osj2Dusers->user_level->CurrentValue = 2;
}
?>
<?php

// Load form values
function LoadFormValues() {

	// Load from form
	global $objForm, $osj2Dusers;
	$osj2Dusers->user_email->setFormValue($objForm->GetValue("x_user_email"));
	$osj2Dusers->user_password->setFormValue($objForm->GetValue("x_user_password"));
	$osj2Dusers->user_level->setFormValue($objForm->GetValue("x_user_level"));
}

// Restore form values
function RestoreFormValues() {
	global $osj2Dusers;
	$osj2Dusers->user_email->CurrentValue = $osj2Dusers->user_email->FormValue;
	$osj2Dusers->user_password->CurrentValue = $osj2Dusers->user_password->FormValue;
	$osj2Dusers->user_level->CurrentValue = $osj2Dusers->user_level->FormValue;
}
?>
<?php

// Render row values based on field settings
function RenderRow() {
	global $conn, $Security, $osj2Dusers;

	// Call Row Rendering event
	$osj2Dusers->Row_Rendering();

	// Common render codes for all row types
	// user_email

	$osj2Dusers->user_email->CellCssStyle = "";
	$osj2Dusers->user_email->CellCssClass = "";

	// user_password
	$osj2Dusers->user_password->CellCssStyle = "";
	$osj2Dusers->user_password->CellCssClass = "";

	// user_level
	$osj2Dusers->user_level->CellCssStyle = "";
	$osj2Dusers->user_level->CellCssClass = "";
	if ($osj2Dusers->RowType == EW_ROWTYPE_VIEW) { // View row
	} elseif ($osj2Dusers->RowType == EW_ROWTYPE_ADD) { // Add row

		// user_email
		$osj2Dusers->user_email->EditCustomAttributes = "";
		$osj2Dusers->user_email->EditValue = ew_HtmlEncode($osj2Dusers->user_email->CurrentValue);

		// user_password
		$osj2Dusers->user_password->EditCustomAttributes = "";
		$osj2Dusers->user_password->EditValue = ew_HtmlEncode($osj2Dusers->user_password->CurrentValue);

		// user_level
		$osj2Dusers->user_level->EditCustomAttributes = "";
		if (!$Security->CanAdmin()) { // System admin
			$osj2Dusers->user_level->EditValue = "********";
		} else {
		$sSqlWrk = "SELECT `user_level_id`, `user_level_name` FROM `osj-user_level`";
		if (trim(strval($osj2Dusers->user_level->CurrentValue)) == "") {
			$sSqlWrk .= " WHERE 0=1";
		} else {
			$sSqlWrk .= " WHERE `user_level_id` = " . ew_AdjustSql($osj2Dusers->user_level->CurrentValue) . "";
		}
		$sSqlWrk .= " AND (" . "`user_level_name` != 'Default' AND `user_level_name`!= 'Administrator'" . ")";
		$rswrk = $conn->Execute($sSqlWrk);
		$arwrk = ($rswrk) ? $rswrk->GetRows() : array();
		if ($rswrk) $rswrk->Close();
		array_unshift($arwrk, array("", "Please Select"));
		$osj2Dusers->user_level->EditValue = $arwrk;
		}
	} elseif ($osj2Dusers->RowType == EW_ROWTYPE_EDIT) { // Edit row
	} elseif ($osj2Dusers->RowType == EW_ROWTYPE_SEARCH) { // Search row
	}

	// Call Row Rendered event
	$osj2Dusers->Row_Rendered();
}
?>
<?php

// Add record
function AddRow() {
	global $conn, $Security, $osj2Dusers;

	// Check if valid User ID
	$bValidUser = FALSE;
	if ($Security->CurrentUserID() <> "" && !$Security->IsAdmin()) { // Non system admin
		$bValidUser = $Security->IsValidUserID($osj2Dusers->user_id->CurrentValue);
		if (!$bValidUser) {
			$_SESSION[EW_SESSION_MESSAGE] = "Unauthorized";
			return FALSE;
		}
	}

	// Check for duplicate key
	$bCheckKey = TRUE;
	$sFilter = $osj2Dusers->SqlKeyFilter();
	if (trim(strval($osj2Dusers->user_id->CurrentValue)) == "") {
		$bCheckKey = FALSE;
	} else {
		$sFilter = str_replace("@user_id@", ew_AdjustSql($osj2Dusers->user_id->CurrentValue), $sFilter); // Replace key value
	}
	if (!is_numeric($osj2Dusers->user_id->CurrentValue)) {
		$bCheckKey = FALSE;
	}
	if ($bCheckKey) {
		$rsChk = $osj2Dusers->LoadRs($sFilter);
		if ($rsChk && !$rsChk->EOF) {
			$_SESSION[EW_SESSION_MESSAGE] = "Duplicate value for primary key";
			$rsChk->Close();
			return FALSE;
		}
	}
	if ($osj2Dusers->user_email->CurrentValue <> "") { // Check field with unique index
		$sFilter = "(`user_email` = '" . ew_AdjustSql($osj2Dusers->user_email->CurrentValue) . "')";
		$rsChk = $osj2Dusers->LoadRs($sFilter);
		if ($rsChk && !$rsChk->EOF) {
			$_SESSION[EW_SESSION_MESSAGE] = "Duplicate value for index or primary key -- `user_email`, value = " . $osj2Dusers->user_email->CurrentValue;
			$rsChk->Close();
			return FALSE;
		}
	}
	$rsnew = array();

	// Field user_email
	$osj2Dusers->user_email->SetDbValueDef($osj2Dusers->user_email->CurrentValue, "");
	$rsnew['user_email'] =& $osj2Dusers->user_email->DbValue;

	// Field user_password
	$osj2Dusers->user_password->SetDbValueDef($osj2Dusers->user_password->CurrentValue, "");
	$rsnew['user_password'] =& $osj2Dusers->user_password->DbValue;

	// Field user_level
	$rsnew['user_level'] = 2; // Set default User Level

	// Call Row Inserting event
	$bInsertRow = $osj2Dusers->Row_Inserting($rsnew);
	if ($bInsertRow) {
		$conn->raiseErrorFn = 'ew_ErrorFn';
		$AddRow = $conn->Execute($osj2Dusers->InsertSQL($rsnew));
		$conn->raiseErrorFn = '';
	} else {
		if ($osj2Dusers->CancelMessage <> "") {
			$_SESSION[EW_SESSION_MESSAGE] = $osj2Dusers->CancelMessage;
			$osj2Dusers->CancelMessage = "";
		} else {
			$_SESSION[EW_SESSION_MESSAGE] = "Insert cancelled";
		}
		$AddRow = FALSE;
	}
	if ($AddRow) {
		$osj2Dusers->user_id->setDbValue($conn->Insert_ID());
		$rsnew['user_id'] =& $osj2Dusers->user_id->DbValue;

		// Call Row Inserted event
		$osj2Dusers->Row_Inserted($rsnew);
		WriteAuditTrailOnAdd($rsnew);
		if ($osj2Dusers->SendEmail) SendEmailOnAdd($rsnew);
	}
	return $AddRow;
}
?>
<?php

// Write Audit Trail start/end for grid update
function WriteAuditTrailDummy($typ) {
	$table = 'osj-users';

	// Write Audit Trail
	$filePfx = "log";
	$curDate = date("Y/m/d");
	$curTime = date("H:i:s");
	$id = ew_ScriptName();
	$user = CurrentUserID();
	$action = $typ;
	ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, "", "", "", "");
}
?>
<?php

// Write Audit Trail (add page)
function WriteAuditTrailOnAdd(&$rs) {
	global $osj2Dusers;
	$table = 'osj-users';

	// Get key value
	$key = "";
	if ($key <> "") $key .= EW_COMPOSITE_KEY_SEPARATOR;
	$key .= $rs['user_id'];

	// Write Audit Trail
	$filePfx = "log";
	$curDate = date("Y/m/d");
	$curTime = date("H:i:s");
	$id = ew_ScriptName();
	$user = CurrentUserID();
	$action = "A";
	$oldvalue = "";
	foreach (array_keys($rs) as $fldname) {
		if ($osj2Dusers->fields[$fldname]->FldDataType <> EW_DATATYPE_BLOB) { // Ignore Blob Field
			$newvalue = ($osj2Dusers->fields[$fldname]->FldDataType == EW_DATATYPE_MEMO) ? "<MEMO>" : $rs[$fldname]; // Memo Field
			ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, $fldname, $key, $oldvalue, $newvalue);
		}
	}
}
?>
<?php

// Send email after add success
function SendEmailOnAdd(&$rs) {
	$sFn = "txt/notify.txt";
	$sTable = 'osj-users';
	$sSubject = $sTable . " record inserted";
	$sAction = "Inserted";

	// Get key value
	$sKey = "";
	if ($sKey <> "") $sKey .= EW_COMPOSITE_KEY_SEPARATOR;
	$sKey .= $rs['user_id'];
	ew_SendNotifyEmail($sFn, $sSubject, $sTable, $sKey, $sAction);
}
?>
<?php

// Page Load event
function Page_Load() {

	//echo "Page Load";
}

// Page Unload event
function Page_Unload() {

	//echo "Page Unload";
}
?>
